// 引入配置
import type { HttpRequestConfig } from 'uview-plus/libs/luch-request/index';
import { requestInterceptors, responseInterceptors } from './interceptors';
import type { IResponse } from './type';

// 引入拦截器配置
export function setupRequest() {
  uni.$u.http.setConfig((defaultConfig: HttpRequestConfig) => {
    /* defaultConfig 为默认全局配置 */
    defaultConfig.baseURL = import.meta.env.VITE_APP_BASE_API;
    return defaultConfig;
  });
  requestInterceptors();
  responseInterceptors();
}

export function request<T = any>(config: HttpRequestConfig): Promise<T> {
  return new Promise((resolve, reject) => {
    console.log('接口入参============》', config);
    uni.$u.http.request(config).then((res: IResponse) => {
      if (!res) {
        resolve(false as T);
        return;
      }
      const { data, rows, total, code } = res;
      console.log('接口返参============》', res);
      if (data) {
        resolve(data as T);
      }
      else if (code === 5152) {
        resolve({ rows, total, code } as T);
      }
      else if (rows) {
        resolve({ rows, total } as T);
      }
      else {
        resolve(false as T);
      }
    }).catch((err: any) => {
      reject(err);
    });
  });
}

export function get<T = any>(config: HttpRequestConfig): Promise<T> {
  return request({ ...config, method: 'GET' });
}

export function post<T = any>(config: HttpRequestConfig): Promise<T> {
  console.log('post', config);
  return request({ ...config, method: 'POST' });
}

export function upload<T = any>(config: HttpRequestConfig): Promise<T> {
  return request({ ...config, method: 'UPLOAD' });
}

export function download<T = any>(config: HttpRequestConfig): Promise<T> {
  return request({ ...config, method: 'DOWNLOAD' });
}

export default setupRequest;
